package cn.iocoder.yudao.module.erp.controller.admin.monthplaninfo;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.util.collection.MapUtils;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.module.crm.dal.dataobject.product.CrmProductCategoryDO;
import cn.iocoder.yudao.module.crm.dal.mysql.product.CrmProductCategoryMapper;
import cn.iocoder.yudao.module.crm.service.product.CrmProductCategoryService;
import cn.iocoder.yudao.module.erp.controller.admin.contractinfo.vo.ContractInfoSimpleVO;
import cn.iocoder.yudao.module.erp.controller.admin.planinfo.vo.PlanBuyInfoRespVO;
import cn.iocoder.yudao.module.erp.controller.admin.planinfo.vo.PlanInfoRespVO;
import cn.iocoder.yudao.module.erp.dal.dataobject.contractinfo.ContractInfoDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.customerinfo.CustomerInfoDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.planinfo.PlanInfoDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.product.ErpProductCategoryDO;
import cn.iocoder.yudao.module.erp.dal.mysql.contractinfo.ContractInfoMapper;
import cn.iocoder.yudao.module.erp.dal.mysql.customerinfo.CustomerInfoMapper;
import cn.iocoder.yudao.module.erp.dal.mysql.monthplaninfo.MonthPlanInfoMapper;
import cn.iocoder.yudao.module.erp.dal.mysql.product.ErpProductCategoryMapper;
import cn.iocoder.yudao.module.erp.service.customerinfo.CustomerInfoService;
import cn.iocoder.yudao.module.erp.service.product.ErpProductCategoryService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import javax.validation.constraints.*;
import javax.validation.*;
import javax.servlet.http.*;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.io.IOException;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;

import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.*;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertList;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertSet;
import static cn.iocoder.yudao.module.erp.enums.ErrorCodeConstants.MONTH_PLAN_INFO_NOT_EXISTS;

import cn.iocoder.yudao.module.erp.controller.admin.monthplaninfo.vo.*;
import cn.iocoder.yudao.module.erp.dal.dataobject.monthplaninfo.MonthPlanInfoDO;
import cn.iocoder.yudao.module.erp.service.monthplaninfo.MonthPlanInfoService;

@Tag(name = "管理后台 - 月度计划")
@RestController
@RequestMapping("/erp/month-plan-info")
@Validated
public class MonthPlanInfoController {

    @Resource
    private MonthPlanInfoService monthPlanInfoService;

    @Resource
    private MonthPlanInfoMapper monthPlanInfoMapper;

    @Resource
    private CustomerInfoService customerInfoService;


    @Resource
    private CustomerInfoMapper customerInfoMapper;
    @Resource
    private ContractInfoMapper contractInfoMapper;

    @Resource
    private CrmProductCategoryService crmproductCategoryService;

    @Resource
    private ErpProductCategoryService erpProductCategoryService;


    @PostMapping("/create")
    @Operation(summary = "创建月度计划")
    @PreAuthorize("@ss.hasPermission('erp:month-plan-info:create')")
    public CommonResult<Long> createMonthPlanInfo(@Valid @RequestBody MonthPlanInfoSaveReqVO createReqVO) {
        return success(monthPlanInfoService.createMonthPlanInfo(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新月度计划")
    @PreAuthorize("@ss.hasPermission('erp:month-plan-info:update')")
    public CommonResult<Boolean> updateMonthPlanInfo(@Valid @RequestBody MonthPlanInfoUpdateReqVO updateReqVO) {
        monthPlanInfoService.updateMonthPlanInfo(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除月度计划")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('erp:month-plan-info:delete')")
    public CommonResult<Boolean> deleteMonthPlanInfo(@RequestParam("id") Long id) {
        monthPlanInfoService.deleteMonthPlanInfo(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得月度计划")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('erp:month-plan-info:query')")
    public CommonResult<MonthPlanInfoRespVO> getMonthPlanInfo(@RequestParam("id") Long id) {
        MonthPlanInfoDO monthPlanInfo = monthPlanInfoService.getMonthPlanInfo(id);
        return success(BeanUtils.toBean(monthPlanInfo, MonthPlanInfoRespVO.class));
    }



    @GetMapping("/getNameisExist")
    @Operation(summary = "查询名称是否已存在")
 /*   @Parameter(name = "id", description = "编号", required = true, example = "1024")*/
    /*@PreAuthorize("@ss.hasPermission('erp:month-plan-info:query')")*/
    public CommonResult<Boolean> getNameisExist(/*@RequestParam("name") String name*/NameExistVO exist) {
        //MonthPlanInfoDO monthPlanInfo = monthPlanInfoService.getMonthPlanInfo(id);
        if(StringUtils.isBlank(exist.getName())){
            //throw exception(MONTH_PLAN_INFO_NOT_EXISTS);
            return success(false);
        }
       Long count= monthPlanInfoMapper.selectCount(new LambdaQueryWrapperX<MonthPlanInfoDO>().eq(MonthPlanInfoDO::getName,exist.getName()).neIfPresent(MonthPlanInfoDO::getId,exist.getId()));
       if(count>0){
           return success(false);
       }else{
           return success(true);
       }


    }

    @Resource(name = "crmProductCategoryMapper")
    private CrmProductCategoryMapper productCategoryMapper;

    @Resource
    private ErpProductCategoryMapper erpProductCategoryMapper;


    @GetMapping("/page")
    @Operation(summary = "获得月度计划分页")
    @PreAuthorize("@ss.hasPermission('erp:month-plan-info:query')")
    public CommonResult<PageResult<MonthPlanInfoRespVO>> getMonthPlanInfoPage(@Valid MonthPlanInfoPageReqVO pageReqVO) {
        PageResult<MonthPlanInfoDO> pageResult = monthPlanInfoService.getMonthPlanInfoPage(pageReqVO);
        if (CollUtil.isEmpty(pageResult.getList())) {
            return success(PageResult.empty(pageResult.getTotal()));
        }
       //
        List<MonthPlanInfoRespVO> rlist=buildList(pageResult.getList());
        PageResult<MonthPlanInfoRespVO> rpage=BeanUtils.toBean(pageResult, MonthPlanInfoRespVO.class);
        rpage.setList(rlist);
        return success(rpage);

       // return success(BeanUtils.toBean(pageResult, MonthPlanInfoRespVO.class));
    }


    public List<MonthPlanInfoRespVO> buildList(List<MonthPlanInfoDO> list){
        List<Long> customerIds=list.stream().flatMap(item-> Stream.of(item.getBuyCustomerId(),item.getSaleCustomerId())).collect(Collectors.toList());
        List<CustomerInfoDO> customerList = customerInfoService.getCustomerListIds(customerIds);

        Map<Long,CustomerInfoDO> customerMap=customerList.stream().collect(Collectors.toMap(CustomerInfoDO::getId, e -> e));
        //  return success(BeanUtils.toBean(pageResult, PlanInfoRespVO.class));

        //合同信息
        List<Long> contractIds=list.stream().flatMap(item-> Stream.of(item.getBuyContractId(),item.getSaleContractId())).collect(Collectors.toList());
        List<ContractInfoDO> contractInfoDOList = contractInfoMapper.selectList(new LambdaQueryWrapperX<ContractInfoDO>().in(ContractInfoDO::getId,contractIds));

        Map<Long,ContractInfoDO> contractMap=contractInfoDOList.stream().collect(Collectors.toMap(ContractInfoDO::getId, e -> e));


        Map<Long, CrmProductCategoryDO> upMap =new HashMap<>();
        Map<Long, ErpProductCategoryDO> downloadMap =new HashMap<>();

        Set<Long> upIds=convertSet(list, MonthPlanInfoDO::getUpId);
        if(upIds!=null&&upIds.size()>0){
            List<CrmProductCategoryDO> uplist= productCategoryMapper.selectBatchIds(upIds);
            upMap=uplist.stream().collect(Collectors.toMap(CrmProductCategoryDO::getId, e -> e));
        }


        Set<Long> downloadIds=convertSet(list, MonthPlanInfoDO::getDownloadId);
        if(downloadIds!=null&&downloadIds.size()>0){
            List<ErpProductCategoryDO> dllist= erpProductCategoryMapper.selectBatchIds(downloadIds);
            downloadMap=dllist.stream().collect(Collectors.toMap(ErpProductCategoryDO::getId, e -> e));
        }


        List<MonthPlanInfoRespVO> rlist=BeanUtils.toBean(list, MonthPlanInfoRespVO.class);
        for(MonthPlanInfoRespVO plan:rlist){
            MapUtils.findAndThen(customerMap, plan.getBuyCustomerId(), cus -> plan.setBuyCustomerName(cus.getName()));
            MapUtils.findAndThen(customerMap, plan.getSaleCustomerId(), cus -> plan.setSaleCustomerName(cus.getName()));

            MapUtils.findAndThen(contractMap, plan.getBuyContractId(), cus -> plan.setBuyContractName(cus.getName()));

            MapUtils.findAndThen(contractMap, plan.getSaleContractId(), cus -> plan.setSaleContractName(cus.getName()));

            MapUtils.findAndThen(upMap, plan.getUpId(),
                    l -> plan.setUpName(l.getShortName()));

            MapUtils.findAndThen(downloadMap, plan.getDownloadId(),
                    l -> plan.setDownloadName(l.getShortName()));

            BigDecimal profit=plan.getSaleAllCost().subtract(plan.getBuyAllCost()).subtract(plan.getLineCost()).subtract(plan.getBuyOtherTotal()).subtract(plan.getSaleOtherTotal());

            plan.setProfit(profit);

            //照付不议描述
            BigDecimal needFinsh=plan.getCapacityTotal().multiply(plan.getRatio()).setScale(2, RoundingMode.HALF_UP);
            if(plan.getUsedDownCount().compareTo(needFinsh)>=0){
                plan.setRatioFinish(true);
                plan.setRatioDescible("已完成");
            }else{
                plan.setRatioFinish(false);
                BigDecimal lack=needFinsh.subtract(plan.getUsedDownCount());
                BigDecimal strippedNumber = lack.stripTrailingZeros();
                plan.setRatioDescible("剩余照付不议量："+strippedNumber.toPlainString());
            }
        }

        return rlist;
    }


    @GetMapping("/findMonthPlanList")
    @Operation(summary = "获得月度计划列表，主要用于前端的下拉选项")
/*    @PreAuthorize("@ss.hasPermission('erp:month-plan-info:query')")*/
    public CommonResult<List<MonthPlanInfoRespVO>> findMonthPlanList(MonthPlanInfoPageReqVO pageReqVO) {
       // PageResult<MonthPlanInfoDO> pageResult = monthPlanInfoService.getMonthPlanInfoPage(pageReqVO);
        List<MonthPlanInfoDO> list=monthPlanInfoMapper.selectList(new LambdaQueryWrapperX<MonthPlanInfoDO>().orderByDesc(MonthPlanInfoDO::getCreateTime));
        return success(BeanUtils.toBean(list, MonthPlanInfoRespVO.class));
    }


    @GetMapping("/simple-list")
    @Operation(summary = "获得月度计划精简列表", description = "获得月度计划精简列表，主要用于前端的下拉选项")
    public CommonResult<List<MonthPlanSimpleVO>> getProductCategorySimpleList() {
        List<MonthPlanInfoDO> list=monthPlanInfoMapper.selectList(new LambdaQueryWrapperX<MonthPlanInfoDO>().select(MonthPlanInfoDO::getId,MonthPlanInfoDO::getName)
                .orderByDesc(MonthPlanInfoDO::getCreateTime));
       /* return success(convertList(list, customer -> new ContractInfoSimpleVO().setId(customer.getId()).setName(customer.getName())));*/
        return success(BeanUtils.toBean(list, MonthPlanSimpleVO.class));
    }


    @GetMapping("/export-excel")
    @Operation(summary = "导出月度计划 Excel")
    @PreAuthorize("@ss.hasPermission('erp:month-plan-info:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportMonthPlanInfoExcel(@Valid MonthPlanInfoPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<MonthPlanInfoDO> list = monthPlanInfoService.getMonthPlanInfoPage(pageReqVO).getList();

        if(list.size()>0){
            // 客户信息
            /*List<CustomerInfoDO> customerList = customerInfoMapper.selectList(new LambdaQueryWrapperX<CustomerInfoDO>().select(CustomerInfoDO::getId,CustomerInfoDO::getName));
            Map<Long,String> customerMap=customerList.stream().collect(Collectors.toMap(CustomerInfoDO::getId, CustomerInfoDO::getName));

            //合同信息
            List<ContractInfoDO> contractInfoDOList = contractInfoMapper.selectList(new LambdaQueryWrapperX<ContractInfoDO>().select(ContractInfoDO::getId,ContractInfoDO::getName));

            Map<Long,String> contractMap=contractInfoDOList.stream().collect(Collectors.toMap(ContractInfoDO::getId, ContractInfoDO::getName));


            Map<Long, CrmProductCategoryDO> upMap = crmproductCategoryService.getProductCategoryMap(
                    convertSet(list, MonthPlanInfoDO::getUpId));

            Map<Long, ErpProductCategoryDO> downMap = erpProductCategoryService.getProductCategoryMap(
                    convertSet(list, MonthPlanInfoDO::getDownloadId));



            List<MonthPlanInfoRespVO> rlist= BeanUtils.toBean(list, MonthPlanInfoRespVO.class, plan -> {
                MapUtils.findAndThen(customerMap, plan.getBuyCustomerId(), cus -> plan.setBuyCustomerName(cus));

                MapUtils.findAndThen(contractMap, plan.getBuyContractId(), cus -> plan.setBuyContractName(cus));


                MapUtils.findAndThen(customerMap, plan.getSaleCustomerId(), cus -> plan.setSaleCustomerName(cus));

                MapUtils.findAndThen(contractMap, plan.getSaleContractId(), cus -> plan.setSaleContractName(cus));


                MapUtils.findAndThen(upMap, plan.getUpId(),
                        l -> plan.setUpName(l.getShortName()));

                MapUtils.findAndThen(downMap, plan.getDownloadId(),
                        l -> plan.setDownloadName(l.getShortName()));
                BigDecimal profit=plan.getSaleAllCost().subtract(plan.getBuyAllCost()).subtract(plan.getLineCost()).subtract(plan.getBuyOtherTotal()).subtract(plan.getSaleOtherTotal());

                plan.setProfit(profit);

            });*/
            List<MonthPlanInfoRespVO> rlist=buildList(list);
            // 导出 Excel
            ExcelUtils.write(response, "月度计划.xls", "数据", MonthPlanInfoRespVO.class,
                    rlist);
        }else{
            // 导出 Excel
            ExcelUtils.write(response, "月度计划.xls", "数据", MonthPlanInfoRespVO.class,
                    BeanUtils.toBean(list, MonthPlanInfoRespVO.class));
        }



    }

}